package com.ferry.serial.jdk;

import com.ferry.serial.api.InputBuf;
import com.ferry.serial.api.OutputBuf;
import com.ferry.serial.api.Serializer;
import com.ferry.serial.api.SerializerType;

import java.io.*;

/**
 * Created by daiyong
 */
public class JdkSerializer extends Serializer {
	@Override
	public int code() {
		return SerializerType.JDK.getCode();
	}

	@Override
	public <T> OutputBuf writeObject(OutputBuf outputBuf, T obj) {
		try (ObjectOutputStream output = new ObjectOutputStream(outputBuf.outputStream())) {
			output.writeObject(obj);
			output.flush();
			return outputBuf;
		} catch (IOException e) {
			throw new RuntimeException("jdk序列化失败");
		}
	}

	@Override
	public <T> byte[] writeObject(T obj) {
		ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
		try (ObjectOutputStream output = new ObjectOutputStream(buf)) {
			output.writeObject(obj);
			output.flush();
			return buf.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException("jdk序列化失败");
		} finally {
			try {
				buf.close();
			} catch (IOException ignored) {
			}
		}
	}

	@Override
	public <T> T readObject(InputBuf inputBuf, Class<T> cls) {
		try (ObjectInputStream input = new ObjectInputStream(inputBuf.inputStream())) {
			Object obj = input.readObject();
			return cls.cast(obj);
		} catch (Exception e) {
			throw new RuntimeException("jdk反序列化失败");
		} finally {
			inputBuf.release();
		}
	}

	@Override
	public <T> T readObject(byte[] bytes, int offset, int length, Class<T> cls) {
		try (ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes, offset, length))) {
			Object obj = input.readObject();
			return cls.cast(obj);
		} catch (Exception e) {
			throw new RuntimeException("jdk反序列化失败");
		}
	}
}
